import { h, defineComponent, ref } from 'vue';
import { Modal, Button } from 'ant-design-vue';
import PromptModal from './index.vue';

export const usePrompt = () => {
  const modalRef = ref();

  const showPrompt = (options = {}) => {
    return new Promise((resolve, reject) => {
      const container = document.createElement('div');
      document.body.appendChild(container);

      const destroy = () => {
        const unmountResult = Modal.destroyAll();
        container.parentNode.removeChild(container);
        resolve(unmountResult);
      };

      const component = h(
        defineComponent({
          setup() {
            const handleOk = (values) => {
              destroy();
              resolve(values);
            };
            const handleCancel = () => {
              destroy();
              reject(new Error('用户取消'));
            };

            return () => h(PromptModal, {
              ref: modalRef,
              title: options.title || '请输入内容',
              fields: options.fields || [
                {
                  name: 'value',
                  label: '输入内容',
                  rules: [{ required: true, message: '请输入内容' }],
                },
              ],
              onOk: handleOk,
              onCancel: handleCancel,
            });
          },
        })
      );

      Modal.info({
        content: () => component,
        footer: null,
        closable: true,
        width: 400,
        // onCancel: handleCancel,
      });
    });
  };

  return { showPrompt };
};